{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9fac0229-04a1-49f1-95cf-3c7b7d726df0",
   "metadata": {},
   "source": [
    "# Codex Simple Prompt Strategy QA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "63100f60-47ea-4c5b-b3e3-bf2507b9ba76",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import re\n",
    "import time\n",
    "import json\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "from tqdm import tqdm\n",
    "from pprint import pprint\n",
    "from tenacity import retry, stop_after_attempt, wait_chain, wait_fixed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "0fe085fc-a2b4-4a0c-b849-9a93c75459df",
   "metadata": {},
   "outputs": [],
   "source": [
    "openai.api_key = \"sk-\" # Hao's key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9bad441c-d7ea-4322-9c31-8c8a30ae7e60",
   "metadata": {},
   "outputs": [],
   "source": [
    "@retry(wait=wait_chain(*[wait_fixed(3) for i in range(3)] +\n",
    "                       [wait_fixed(5) for i in range(2)] +\n",
    "                       [wait_fixed(10)]))\n",
    "def completion_with_backoff(**kwargs):\n",
    "    return openai.Completion.create(**kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "59bd1369-d939-4aba-b48b-a4f34ccc4b95",
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data = json.load(open('data/strategyqa_train.json'))\n",
    "train_filtered = json.load(open('data/strategyqa_train_filtered.json'))\n",
    "train_data_paragraphs = json.load(open('data/strategyqa_train_paragraphs.json'))\n",
    "test_data = json.load(open('data/strategyqa_test.json'))\n",
    "dev_idx = np.load('data/dev_idx.npy')\n",
    "dev_data = [train_data[i] for i in dev_idx]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e0e2ef4d-0ece-4a6e-b053-63b31f41d665",
   "metadata": {},
   "outputs": [],
   "source": [
    "def extract_ans(ans_model):\n",
    "    ans_model = ans_model.split('\\n')\n",
    "    ans = []\n",
    "    residual = []\n",
    "    for li, al in enumerate(ans_model):\n",
    "        ans.append(al)\n",
    "        if('answer is' in al):\n",
    "            break\n",
    "    residual = list(ans_model[li + 1:])\n",
    "    ans = '\\n'.join(ans)\n",
    "    residual = '\\n'.join(residual)\n",
    "    return ans, residual"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a36fd50c-f766-48ec-b18b-8fb2d9de318f",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_simple_step = open('lib_prompt/prompt_simple_step.txt').read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "538f7fe9-b0ab-42fa-b8b3-c80cb30c0e22",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 800/800 [2:32:09<00:00, 11.41s/it]\n"
     ]
    }
   ],
   "source": [
    "acc = 0\n",
    "total = 0\n",
    "with open('outputs/dev_codex_simple_step.txt', 'w') as fd:\n",
    "    for d in tqdm(dev_data):\n",
    "        q = d['question']\n",
    "        a = d['answer']\n",
    "        if(a is True): a = 'yes'\n",
    "        else: a = 'no'\n",
    "        \n",
    "        prompt_q = prompt_simple_step + '\\nQ: ' + q + '\\n'\n",
    "        prompt_q += 'A:'\n",
    "\n",
    "        response = completion_with_backoff(model=\"code-davinci-002\", \n",
    "                                            prompt=prompt_q, \n",
    "                                            temperature=0, \n",
    "                                            max_tokens=256)\n",
    "\n",
    "        ans_model = response['choices'][0]['text']\n",
    "        ans_model, _ = extract_ans(ans_model)\n",
    "        fd.write('Q: %s\\nA_model:\\n%s\\nA:\\n%s\\n\\n' % (q, ans_model, a))\n",
    "        \n",
    "        ans_ = ans_model.split('answer is ')\n",
    "        if(len(ans_) > 1 and 'yes' in ans_[1]): ans_ = 'yes'\n",
    "        else: ans_ = 'no'\n",
    "        \n",
    "        if(ans_ == a): acc += 1\n",
    "        total += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "e34ac9e0-ed74-476c-8097-3e48b51aec80",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total 800 correct 595 acc 0.7438\n"
     ]
    }
   ],
   "source": [
    "print('Total %d correct %d acc %.4f' % (total, acc, acc / total))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
